<?php

namespace app\home\controller;

use app\common\controller\Home;

class Comment extends Home
{
    public function __construct()
    {
        parent::__construct();
        $this->CommentModel = model('Post.Comment');
        $this->UserModel = model('User.User');
        $this->PostModel = model('Post.Post');
        $this->RecordModel = model('Record');
    }

    public function add()
    {
        $action = $this->request->param('action');
        if ($action == 'add') {
            //接收评论内容
            $content = $this->request->param('content');

            // 用户id
            $userid = isset($this->LoginUser['id']) ? $this->LoginUser['id'] : 0;

            // 评论上一级id
            $pid = $this->request->param('pid', '0');

            // 帖子id
            $postid = $this->request->param('postid');

            $post = model('Post.Post')->find($postid);

            if (!$post) {
                $this->error('当前评论帖子不存在');
            }

            $data = [
                'content' => $content,
                'userid' => $userid,
                'postid' => $postid,
                'pid' => $pid,
                'accept' => 0
            ];

            $comment = $this->CommentModel->find($pid);

            if ($comment) {
                $data['level'] = $comment['level'] + 1;
            } else {
                $data['level'] = 0;
            }

            $result = $this->CommentModel->validate('common/Post/Comment')->save($data);


            if ($result === FALSE) {
                $this->error($this->CommentModel->getError());
            } else {
                $this->success('评论成功');
            }
        }
    }

    //采纳
    public function accept()
    {

        $action = $this->request->param('action');
        if ($action == 'accept') {
            $comid = $this->request->param('comid');
            $comment = $this->CommentModel->with('post')->find($comid);

            if (!$comment) {
                $this->error('该评论不存在，无法采纳');
            }

            /**
             * 评论表 => accept = 1
             * 帖子表 => accept = userid
             * 用户表 =>用户表 => accept => userid = 加积分
             * 消费记录表 => accept => userid = 新增记录
             */

            // 开启事务 => 操作多个表 => 更新或者新增 => 当某个表新增或者更新失败，它可以让操作的表撤回新增或者更新的数据
            $this->CommentModel->startTrans();
            $this->UserModel->startTrans();
            $this->PostModel->startTrans();
            $this->RecordModel->startTrans();

            // 更新评论表数据
            $CommentData = [
                'id' => $comid,
                'accept' => 1
            ];

            $CommentStatus = $this->CommentModel->isUpdate(true)->save($CommentData);

            if ($CommentStatus === FALSE) {
                $this->error($this->CommentModel->getError());
            }

            // 获取悬赏积分 => 获取用户的积分
            $User = $this->UserModel->find($comment['userid']);

            if (!$User) {
                $this->error('该用户不存在');
            }

            $UpdatePonit = bcadd($User['point'], $comment['post']['point']);

            $UserData = [
                'id' => $comment['userid'],
                'point' => $UpdatePonit
            ];

            $UserStatus = $this->UserModel->isUpdate(true)->save($UserData);

            if ($UserStatus === FALSE) {
                $this->CommentModel->rollback();
                $this->error($this->UserModel->getError);
            }

            // 帖子
            $PostData = [
                'id' => $comment['postid'],
                'accept' => $comment['userid']
            ];

            $PostStatus = $this->PostModel->isUpdate(true)->save($PostData);

            if ($PostStatus === FALSE) {
                $this->CommentModel->rollback();
                $this->UserModel->rollback();
                $this->error($this->PostModel->getError);
            }

            // 消费记录
            $RecordData = [
                'point' => $comment['post']['point'],
                'content' => "您在【{$comment['post']['title']}】里评论内容被采纳了，获得了{$comment['post']['point']}积分",
                'state' => 2,
                'userid' => $comment['userid']
            ];

            $RecordStatus = $this->RecordModel->validate('common/User/Record')->save($RecordData);

            if ($RecordStatus === FALSE) {
                $this->CommentModel->rollback();
                $this->UserModel->rollback();
                $this->PostModel->rollback();
                $this->error($this->RecordModel->getError);
            }

            if ($RecordStatus === FALSE || $CommentStatus === FALSE || $UserStatus === FALSE || $PostStatus === FALSE) {
                $this->CommentModel->rollback();
                $this->UserModel->rollback();
                $this->PostModel->rollback();
                $this->RecordModel->rollback();
                $this->error('采纳失败');
            } else {
                $this->CommentModel->commit();
                $this->UserModel->commit();
                $this->PostModel->commit();
                $this->RecordModel->commit();
                $this->success('采纳成功');
            }
        }
    }

    //点赞
    public function like()
    {
        $action = $this->request->param('action');

        if ($action == 'zan') {
            $comid = $this->request->param('comid');
            $userid = $this->request->param('userid');
            $comment = $this->CommentModel->find($comid);
            if (strpos($comment['like'], $userid) !== false) {
                $arr = explode(',', $comment['like']);
                $arr = array_filter($arr, function ($k) {
                    return $k !== $this->request->param('userid');
                });
                $count = count($arr);
                $arr = implode(",", $arr);
                $result = $this->CommentModel->where('id', $comid)->update(['like' => $arr]);

                if ($result == FALSE) {
                    $this->error('取消点赞失败');
                } else {
                    $this->success('已取消点赞', '', [$count, 'unzan']);
                }
            } else {
                $result = $this->CommentModel->where('id', $comid)->update(['like' => trim($comment['like'] . ',' . $userid, ',')]);
                if ($result == FALSE) {
                    $this->error('点赞失败');
                } else {
                    $this->success('点赞成功', '', [count(explode(',', trim($comment['like'] . ',' . $userid, ','))), 'zan']);
                }
            }
        }
    }

    //评论删除
    public function commentDel()
    {
        $commentDel = $this->request->param('action');
        if ($commentDel == 'commentDel') {
            $comid = $this->request->param('comid');
            $arr[] = (int)$comid;
            $comid = $this->CommentModel->where('pid', $comid)->value('id');
            $arr[] = $comid;
            while (!empty($comid)) {
                $comid = $this->CommentModel->where('pid', $comid)->value('id');
                $arr[] = $comid;
            }
            $result = $this->CommentModel->destroy($arr);
            if ($result == FALSE) {
                $this->error('删除失败');
            } else {
                $this->success('删除成功');
            }
        }
    }
}
